import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import 'package:google_fonts/google_fonts.dart';
import '../constants/app_colors.dart';
import '../constants/app_theme.dart';
import '../models/mood.dart';
import '../providers/mood_provider.dart';
import '../widgets/mood_selector.dart';
import '../widgets/hand_drawn_decoration.dart';
import '../widgets/hand_drawn_icon.dart';
import '../widgets/hand_drawn_emoji.dart';
import '../widgets/hand_drawn_trigger_icon.dart';
import '../widgets/hand_drawn_body_reaction_icon.dart';
import '../widgets/hand_drawn_input_icon.dart';
import '../constants/hand_drawn_trigger_icon_type.dart';
import '../constants/hand_drawn_body_reaction_icon_type.dart';
import '../constants/hand_drawn_input_icon_type.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import '../models/database_helper.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'dart:convert';

class MoodScreen extends StatefulWidget {
  const MoodScreen({Key? key}) : super(key: key);

  @override
  State<MoodScreen> createState() => _MoodScreenState();
}

class _MoodScreenState extends State<MoodScreen> {
  int _currentStep = 0;
  int _moodIntensity = 5;
  int _selectedMood = 3;
  bool _isLoading = false;
  dynamic _selectedImage;
  String? _webImageData;
  final _picker = ImagePicker();
  final Set<String> _selectedTriggers = {};
  final Set<String> _selectedBodyReactions = {};
  final Set<String> _selectedEmotions = {};
  final TextEditingController _descriptionController = TextEditingController();
  final DatabaseHelper _dbHelper = DatabaseHelper.instance;
  
  List<Map<String, dynamic>> _triggerCategories = [];
  List<Map<String, dynamic>> _bodyReactionCategories = [];
  Set<String> _expandedCategories = {};
  
  final Map<String, List<String>> _emotionTags = {
    'positive': [
      '惊奇', '兴奋', '惊讶', '热衷', '开心', '欢乐', '勇敢', '自豪', 
      '自信', '满怀希望', '愉悦', '满意', '如释重负', '感恩', '满足', '平静', '平和'
    ],
    'neutral': [
      '满足', '平和', '冷漠', '精疲力尽'
    ],
    'negative': [
      '愤怒', '焦虑', '害怕', '不堪重负', '羞愧', '厌恶', '尴尬', '沮丧', 
      '恼火', '嫉妒', '有压力', '忧虑', '内疚', '惊讶', '无望', '烦躁', 
      '孤独', '挫败', '失望', '精疲力尽', '伤心'
    ],
  };
  
  @override
  void initState() {
    super.initState();
    _resetSelections();
    _initializeData();
  }
  
  void _resetSelections() {
    setState(() {
      _currentStep = 0;
      _moodIntensity = 5;
      _selectedMood = 3;
      _selectedEmotions.clear();
      _selectedTriggers.clear();
      _selectedBodyReactions.clear();
      _descriptionController.clear();
      _selectedImage = null;
      _expandedCategories.clear();
    });
  }
  
  Future<void> _initializeData() async {
    try {
      // 加载情绪诱因和身体反应
      await _loadCategories();
      
      // 加载所有情绪记录
      await _loadMoodRecords();
    } catch (e) {
      debugPrint('初始化数据失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载数据失败: $e')),
        );
      }
    }
  }
  
  Future<void> _loadCategories() async {
    if (!mounted) return;

    setState(() {
      _isLoading = true;
      _triggerCategories = [];
      _bodyReactionCategories = [];
      _selectedTriggers.clear();
      _selectedBodyReactions.clear();
      _expandedCategories.clear();
    });

    try {
      String moodRange = _getMoodRange();
      debugPrint('Loading categories for mood range: $moodRange');
      
      // 重新加载数据
      final triggers = await _dbHelper.getEmotionTriggers(moodRange);
      final reactions = await _dbHelper.getBodyReactions(moodRange);
      
      debugPrint('Loaded triggers: $triggers');
      debugPrint('Loaded reactions: $reactions');
      
      if (!mounted) return;

      // 强制延迟一帧，确保 setState 在下一帧执行
      WidgetsBinding.instance.addPostFrameCallback((_) {
        setState(() {
          _triggerCategories = List<Map<String, dynamic>>.from(triggers);
          _bodyReactionCategories = List<Map<String, dynamic>>.from(reactions);
          _isLoading = false;
          debugPrint('Updated state with ${_triggerCategories.length} triggers and ${_bodyReactionCategories.length} reactions');
        });
      });
    } catch (e) {
      debugPrint('Error loading categories: $e');
      if (!mounted) return;
      
      setState(() {
        _isLoading = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('加载情绪诱因和身体反应失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
  
  Future<void> _loadTodayMood() async {
    try {
      final today = DateFormat('yyyy-MM-dd').format(DateTime.now());
      final moods = await _dbHelper.getMoods();
      final todayMood = moods.firstWhere(
        (mood) => mood.date == today,
        orElse: () => Mood(
          id: 0,
          moodType: 3,
          intensity: 5,
          emotions: [],
          triggers: [],
          bodyReactions: [],
          description: '',
          createdAt: DateTime.now(),
          date: today,
        ),
      );

      if (mounted) {
        setState(() {
          _selectedMood = todayMood.moodType;
          _moodIntensity = todayMood.intensity;
          _selectedEmotions.clear();
          _selectedEmotions.addAll(todayMood.emotions);
          _selectedTriggers.clear();
          _selectedTriggers.addAll(todayMood.triggers);
          _selectedBodyReactions.clear();
          _selectedBodyReactions.addAll(todayMood.bodyReactions);
          _descriptionController.text = todayMood.description;
          if (todayMood.imagePath != null) {
            _selectedImage = File(todayMood.imagePath!);
          }
        });
      }
    } catch (e) {
      debugPrint('加载今日情绪记录失败: $e');
    }
  }

  Future<void> _loadMoodRecords() async {
    try {
      final moods = await _dbHelper.getMoods();
      if (mounted) {
        // 这里可以添加处理所有情绪记录的逻辑
        // 例如：更新统计信息、图表等
      }
    } catch (e) {
      debugPrint('加载情绪记录失败: $e');
    }
  }

  String _getMoodRange() {
    debugPrint('Getting mood range for intensity: $_moodIntensity');
    String range;
    if (_moodIntensity >= 7) {
      range = 'positive';
    } else if (_moodIntensity <= 3) {
      range = 'negative';
    } else {
      range = 'neutral';
    }
    debugPrint('Mood range: $range');
    return range;
  }

  @override
  void dispose() {
    _descriptionController.dispose();
    super.dispose();
  }

  void _nextStep() {
    if (_currentStep < 4) {
      setState(() {
        _currentStep++;
      });
    } else {
      _saveMood();
    }
  }

  void _previousStep() {
    if (_currentStep > 0) {
      setState(() {
        _currentStep--;
      });
    }
  }

  void _toggleTrigger(String trigger) {
    setState(() {
      if (_selectedTriggers.contains(trigger)) {
        _selectedTriggers.remove(trigger);
      } else {
        _selectedTriggers.add(trigger);
      }
    });
  }

  void _toggleBodyReaction(String reaction) {
    setState(() {
      if (_selectedBodyReactions.contains(reaction)) {
        _selectedBodyReactions.remove(reaction);
      } else {
        _selectedBodyReactions.add(reaction);
      }
    });
  }

  Future<void> _pickImage() async {
    try {
      final XFile? pickedFile = await _picker.pickImage(source: ImageSource.gallery);
      
      if (pickedFile != null) {
        if (kIsWeb) {
          // Web platform: Store image as base64 string
          final bytes = await pickedFile.readAsBytes();
          setState(() {
            _webImageData = base64Encode(bytes);
            _selectedImage = pickedFile;
          });
        } else {
          // Mobile platform: Store image as File
          setState(() {
            _selectedImage = File(pickedFile.path);
          });
        }
      }
    } catch (e) {
      debugPrint('Error picking image: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('选择图片失败: $e')),
      );
    }
  }

  Future<String?> _saveImage() async {
    if (_selectedImage == null) return null;

    try {
      if (kIsWeb) {
        // For web, return the base64 string directly
        return _webImageData;
      } else {
        // For mobile, save the file and return the path
        final directory = await getApplicationDocumentsDirectory();
        final fileName = 'mood_${DateTime.now().millisecondsSinceEpoch}.jpg';
        final savedImage = await File(_selectedImage.path)
            .copy('${directory.path}/$fileName');
        return savedImage.path;
      }
    } catch (e) {
      debugPrint('Error saving image: $e');
      return null;
    }
  }

  Widget _buildImagePreview({bool isThumbnail = false}) {
    if (_selectedImage == null) return Container();

    if (kIsWeb) {
      if (_webImageData != null) {
        if (isThumbnail) {
          return Container(
            width: 32,
            height: 32,
            child: Image.memory(
              base64Decode(_webImageData!),
              fit: BoxFit.cover,
            ),
          );
        }
        return Image.memory(
          base64Decode(_webImageData!),
          height: 200,
          fit: BoxFit.cover,
        );
      }
      return Container();
    } else {
      if (isThumbnail) {
        return Container(
          width: 32,
          height: 32,
          child: Image.file(
            _selectedImage as File,
            fit: BoxFit.cover,
          ),
        );
      }
      return Image.file(
        _selectedImage as File,
        height: 200,
        fit: BoxFit.cover,
      );
    }
  }

  void _saveMood() async {
    setState(() => _isLoading = true);
    try {
      final imagePath = await _saveImage();
      final newMood = Mood(
        id: 0,
        moodType: _selectedMood,
        intensity: _moodIntensity,
        emotions: _selectedEmotions.toList(),
        triggers: _selectedTriggers.toList(),
        bodyReactions: _selectedBodyReactions.toList(),
        description: _descriptionController.text,
        createdAt: DateTime.now(),
        date: DateFormat('yyyy-MM-dd').format(DateTime.now()),
        imagePath: imagePath,
      );

      final moodProvider = Provider.of<MoodProvider>(context, listen: false);
      final success = await moodProvider.saveMood(
        moodType: newMood.moodType,
        intensity: newMood.intensity,
        emotions: newMood.emotions,
        triggers: newMood.triggers,
        bodyReactions: newMood.bodyReactions,
        description: newMood.description,
        imagePath: newMood.imagePath,
      );

      if (mounted) {
        setState(() {
          _isLoading = false;
          _descriptionController.clear();
          _selectedImage = null;
        });

        if (success) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('情绪记录已保存！'),
              backgroundColor: AppColors.success,
            ),
          );
          Navigator.pop(context);
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('保存失败，请重试'),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } catch (e) {
      debugPrint('Error saving mood: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('保存失败，请重试'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 当依赖改变时（比如情绪强度改变），重新加载数据
    _loadCategories();
  }

  // 当情绪强度改变时调用此方法
  void _onMoodIntensityChanged(double value) {
    final oldRange = _getMoodRange();
    final oldIntensity = _moodIntensity;
    
    setState(() {
      _moodIntensity = value.round();
    });
    
    final newRange = _getMoodRange();
    
    // 只有当情绪范围改变时才重新加载标签
    if (oldRange != newRange || oldIntensity != _moodIntensity) {
      debugPrint('Mood range changed from $oldRange to $newRange or intensity changed from $oldIntensity to $_moodIntensity');
      _loadCategories();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        title: Text(
          _getStepTitle(),
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            size: 24,
            color: AppColors.textPrimary,
          ),
          onPressed: _currentStep > 0 ? _previousStep : () => Navigator.pop(context),
        ),
      ),
      body: _buildStepContent(),
    );
  }

  String _getStepTitle() {
    switch (_currentStep) {
      case 0:
        return '你现在的情绪强度是？';
      case 1:
        return '哪项最能描述此刻的情绪？';
      case 2:
        return '是什么引发了这种情绪？';
      case 3:
        return '有什么身体反应吗？';
      case 4:
        return '想说点什么吗？';
      default:
        return '记录情绪';
    }
  }

  Widget _buildStepContent() {
    switch (_currentStep) {
      case 0:
        return _buildMoodIntensityStep();
      case 1:
        return _buildEmotionStep();
      case 2:
        return _buildTriggersStep();
      case 3:
        return _buildBodyReactionsStep();
      case 4:
        return _buildDescriptionStep();
      default:
        return Container();
    }
  }

  Widget _buildMoodIntensityStep() {
    String moodText = '平静';
    
    if (_moodIntensity >= 8) {
      moodText = '开心';
    } else if (_moodIntensity >= 6) {
      moodText = '愉快';
    } else if (_moodIntensity >= 4) {
      moodText = '平静';
    } else if (_moodIntensity >= 2) {
      moodText = '低落';
    } else {
      moodText = '难过';
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(24),
      child: Column(
        children: [
          const SizedBox(height: 24),
          
          Container(
            width: 160,
            height: 160,
            child: Center(
              child: HandDrawnEmoji(
                intensity: _moodIntensity.toDouble(),
                size: 120,
                color: AppColors.textPrimary,
              ),
            ),
          ),
          const SizedBox(height: 16),
          Text(
            moodText,
            style: GoogleFonts.zcoolKuaiLe(
              fontSize: 28,
              fontWeight: FontWeight.bold,
              color: AppColors.textPrimary,
            ),
          ),
          const SizedBox(height: 32),
          
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(24),
            ),
            padding: const EdgeInsets.all(24),
            child: Column(
              children: [
                Text(
                  '拖动滑块调节情绪强度',
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 18,
                    color: AppColors.textSecondary,
                  ),
                ),
                const SizedBox(height: 16),
                SliderTheme(
                  data: SliderTheme.of(context).copyWith(
                    activeTrackColor: AppColors.primary,
                    inactiveTrackColor: Colors.grey.shade200,
                    thumbColor: AppColors.primary,
                    overlayColor: AppColors.primary.withOpacity(0.1),
                    trackHeight: 8,
                  ),
                  child: Slider(
                    value: _moodIntensity.toDouble(),
                    min: 0,
                    max: 10,
                    divisions: 10,
                    onChanged: _onMoodIntensityChanged,
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '很弱',
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 14,
                        color: AppColors.textSecondary,
                      ),
                    ),
                    Text(
                      '很强',
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 14,
                        color: AppColors.textSecondary,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          
          const SizedBox(height: 48),
          
          SizedBox(
            width: double.infinity,
            child: TextButton(
              onPressed: _nextStep,
              style: TextButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                backgroundColor: AppColors.primary,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
              ),
              child: Text(
                '下一步',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmotionStep() {
    String moodRange = _getMoodRange();
    List<String> emotions = _emotionTags[moodRange] ?? [];

    return SingleChildScrollView(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '选择最能描述你此刻情绪的词（可选）',
            style: GoogleFonts.zcoolKuaiLe(
              fontSize: 18,
              color: AppColors.textSecondary,
            ),
          ),
          const SizedBox(height: 24),
          
          if (emotions.isEmpty)
            Center(
              child: Text(
                '请先选择情绪强度',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 16,
                  color: AppColors.textSecondary,
                ),
              ),
            )
          else
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: emotions.map((emotion) => _buildEmotionChip(emotion)).toList(),
            ),
          
          const SizedBox(height: 48),
          
          SizedBox(
            width: double.infinity,
            child: TextButton(
              onPressed: _nextStep,
              style: TextButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                backgroundColor: AppColors.primary,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
              ),
              child: Text(
                '下一步',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmotionChip(String emotion) {
    final isSelected = _selectedEmotions.contains(emotion);
    return GestureDetector(
      onTap: () {
        setState(() {
          if (isSelected) {
            _selectedEmotions.remove(emotion);
          } else {
            _selectedEmotions.add(emotion);
          }
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? AppColors.primary : Colors.white,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: isSelected ? AppColors.primary : Colors.grey.shade300,
            width: 1,
          ),
        ),
        child: Text(
          emotion,
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 16,
            color: isSelected ? Colors.white : AppColors.textPrimary,
          ),
        ),
      ),
    );
  }

  Widget _buildTriggersStep() {
    if (_triggerCategories.isEmpty) {
      return Center(
        child: CircularProgressIndicator(),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '选择触发因素（可多选）',
            style: GoogleFonts.zcoolKuaiLe(
              fontSize: 18,
              color: AppColors.textSecondary,
            ),
          ),
          const SizedBox(height: 24),
          
          ListView.separated(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: _triggerCategories.length,
            separatorBuilder: (context, index) => const SizedBox(height: 16),
            itemBuilder: (context, index) {
              final category = _triggerCategories[index];
              final categoryName = category['category_name'] as String;
              final triggers = (category['triggers'] as String).split(',');
              final isExpanded = _expandedCategories.contains(categoryName);
              final displayTriggers = isExpanded ? triggers : triggers.take(4).toList();
              final hasMore = triggers.length > 4;
              
              return Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16),
                  border: Border.all(
                    color: Colors.grey.shade200,
                    width: 1,
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      categoryName,
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 12),
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        ...displayTriggers.map((trigger) => _buildTriggerChip(trigger)),
                        if (hasMore)
                          TextButton(
                            onPressed: () {
                              setState(() {
                                if (isExpanded) {
                                  _expandedCategories.remove(categoryName);
                                } else {
                                  _expandedCategories.add(categoryName);
                                }
                              });
                            },
                            child: Text(
                              isExpanded ? '收起' : '展开更多',
                              style: GoogleFonts.zcoolKuaiLe(
                                color: AppColors.primary,
                                fontSize: 16,
                              ),
                            ),
                          ),
                      ],
                    ),
                  ],
                ),
              );
            },
          ),
          
          const SizedBox(height: 48),
          
          SizedBox(
            width: double.infinity,
            child: TextButton(
              onPressed: _nextStep,
              style: TextButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                backgroundColor: AppColors.primary,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
              ),
              child: Text(
                '下一步',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTriggerChip(String trigger) {
    final isSelected = _selectedTriggers.contains(trigger);
    return GestureDetector(
      onTap: () {
        setState(() {
          if (isSelected) {
            _selectedTriggers.remove(trigger);
          } else {
            _selectedTriggers.add(trigger);
          }
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? AppColors.primary : Colors.white,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: isSelected ? AppColors.primary : Colors.grey.shade300,
            width: 1,
          ),
        ),
        child: Text(
          trigger,
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 16,
            color: isSelected ? Colors.white : AppColors.textPrimary,
          ),
        ),
      ),
    );
  }

  Widget _buildBodyReactionsStep() {
    debugPrint('Building body reactions step with ${_bodyReactionCategories.length} categories');
    
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (_bodyReactionCategories.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '暂无数据',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 18,
                color: AppColors.textSecondary,
              ),
            ),
            const SizedBox(height: 16),
            TextButton(
              onPressed: _loadCategories,
              child: Text(
                '重新加载',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 16,
                  color: AppColors.primary,
                ),
              ),
            ),
          ],
        ),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '选择身体反应（可多选）',
            style: GoogleFonts.zcoolKuaiLe(
              fontSize: 18,
              color: AppColors.textSecondary,
            ),
          ),
          const SizedBox(height: 24),
          
          ListView.separated(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: _bodyReactionCategories.length,
            separatorBuilder: (context, index) => const SizedBox(height: 16),
            itemBuilder: (context, index) {
              final category = _bodyReactionCategories[index];
              final categoryName = category['category_name'] as String;
              final reactions = (category['reactions'] as String).split(',');
              final isExpanded = _expandedCategories.contains(categoryName);
              final displayReactions = isExpanded ? reactions : reactions.take(4).toList();
              final hasMore = reactions.length > 4;
              
              return Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16),
                  border: Border.all(
                    color: Colors.grey.shade200,
                    width: 1,
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      categoryName,
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 12),
                    Wrap(
                      spacing: 8,
                      runSpacing: 8,
                      children: [
                        ...displayReactions.map((reaction) => _buildReactionChip(reaction)),
                        if (hasMore)
                          TextButton(
                            onPressed: () {
                              setState(() {
                                if (isExpanded) {
                                  _expandedCategories.remove(categoryName);
                                } else {
                                  _expandedCategories.add(categoryName);
                                }
                              });
                            },
                            child: Text(
                              isExpanded ? '收起' : '展开更多',
                              style: GoogleFonts.zcoolKuaiLe(
                                color: AppColors.primary,
                                fontSize: 16,
                              ),
                            ),
                          ),
                      ],
                    ),
                  ],
                ),
              );
            },
          ),
          
          const SizedBox(height: 48),
          
          SizedBox(
            width: double.infinity,
            child: TextButton(
              onPressed: _nextStep,
              style: TextButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                backgroundColor: AppColors.primary,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
              ),
              child: Text(
                '下一步',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildReactionChip(String reaction) {
    final isSelected = _selectedBodyReactions.contains(reaction);
    return GestureDetector(
      onTap: () {
        setState(() {
          if (isSelected) {
            _selectedBodyReactions.remove(reaction);
          } else {
            _selectedBodyReactions.add(reaction);
          }
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? AppColors.primary : Colors.white,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: isSelected ? AppColors.primary : Colors.grey.shade300,
            width: 1,
          ),
        ),
        child: Text(
          reaction,
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 16,
            color: isSelected ? Colors.white : AppColors.textPrimary,
          ),
        ),
      ),
    );
  }

  Widget _buildDescriptionStep() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '记录一下此刻的想法...',
            style: GoogleFonts.zcoolKuaiLe(
              fontSize: 18,
              color: AppColors.textSecondary,
            ),
          ),
          const SizedBox(height: 24),
          
          // 描述输入框
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
            ),
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                TextField(
                  controller: _descriptionController,
                  maxLines: 5,
                  maxLength: 500,
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 18,
                    color: AppColors.textPrimary,
                  ),
                  decoration: InputDecoration(
                    hintText: '写下你的感受、想法，或者任何想说的话...',
                    hintStyle: GoogleFonts.zcoolKuaiLe(
                      fontSize: 18,
                      color: AppColors.textSecondary,
                    ),
                    border: InputBorder.none,
                    counterStyle: GoogleFonts.zcoolKuaiLe(
                      fontSize: 14,
                      color: AppColors.textSecondary,
                    ),
                  ),
                ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _buildInputOptionButton(
                      icon: Icons.mic,
                      label: '录音',
                      onTap: () {
                        // TODO: 实现语音输入
                      },
                    ),
                    _buildInputOptionButton(
                      icon: Icons.image,
                      label: '图片',
                      onTap: _pickImage,
                    ),
                  ],
                ),
              ],
            ),
          ),
          
          const SizedBox(height: 48),
          
          // 保存按钮
          SizedBox(
            width: double.infinity,
            child: TextButton(
              onPressed: _isLoading ? null : _saveMood,
              style: TextButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                backgroundColor: AppColors.primary,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(16),
                ),
              ),
              child: _isLoading
                  ? SizedBox(
                      width: 24,
                      height: 24,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                  : Text(
                      '保存',
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInputOptionButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    if (icon == Icons.image && _selectedImage != null) {
      return GestureDetector(
        onTap: onTap,
        child: Container(
          width: 120,
          height: 48,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(24),
            border: Border.all(
              color: Colors.grey.shade200,
              width: 1,
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Container(
                  width: 32,
                  height: 32,
                  child: _buildImagePreview(isThumbnail: true),
                ),
              ),
              const SizedBox(width: 8),
              Text(
                '重新选择',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 16,
                  color: AppColors.textPrimary,
                ),
              ),
            ],
          ),
        ),
      );
    }

    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 120,
        height: 48,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(24),
          border: Border.all(
            color: Colors.grey.shade200,
            width: 1,
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            HandDrawnInputIcon(
              type: icon == Icons.mic ? HandDrawnInputIconType.mic : HandDrawnInputIconType.image,
              size: 24,
              color: AppColors.textPrimary,
            ),
            const SizedBox(width: 8),
            Text(
              label,
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 16,
                color: AppColors.textPrimary,
              ),
            ),
          ],
        ),
      ),
    );
  }
} 